package com.test.server.handler;

import com.test.model.Connection;
import com.test.model.ConnectionManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 在规定时间内未收到客户端的任何数据包, 将主动断开该连接
 */
@Slf4j
public class ServerIdleStateTrigger extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        Connection conn = ctx.channel().attr(ConnectionManager.connection).get();
        if (conn == null) {
            return;
        }

        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                //TODO  在规定时间内没有收到客户端的上行数据, 主动断开连接
//                ctx.channel().close();
                log.debug("设备号：{},长时间未响应", conn.getImei());
//                log.debug("设备号：{},长时间未响应，断开连接", conn.getImei());
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}